import 'dart:io';
import 'package:flutter/material.dart';
import 'package:heven/api/index.dart';
import 'package:heven/model/config_model.dart';
import 'package:heven/pages/home/home.dart';
import 'package:heven/pages/login/list.dart';

import 'package:heven/utils/index.dart';
import 'routes.dart';
import 'package:provider/provider.dart';
import 'package:heven/state/music.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized(); // 确保 Flutter 框架已初始化

  // 初始化 FlutterForegroundTask 通信端口
  FlutterForegroundTask.initCommunicationPort();

  await Common.getPackageInfo();
  var token = await Common.getStorageValue('token');

  var workStatus = await Common.checkNetworkStatus();
  var isExitStr = await Common.getStorageValue('isExit');

  if (token == null && workStatus && isExitStr != '1') {
    print('111');
    try {
      refreshToken(); // 这里可以调用登录接口
      var config = await getConfig();
      // ConfigModel configModel = ConfigModel.fromJson(config);
      await Common.saveStorageValue('artConsumeCoinNumber',
          config['art_consume_coin_number']['value'].toString());
    } catch (e) {
      print("登录失败：$e");
    }
  }
  bool homeBool = token == null && isExitStr == '1';
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => MusicState()),
      ],
      child: MyApp(home: homeBool),
    ),
  );
}

// The callback function should always be a top-level or static function. @pragma('vm:entry-point')
void startCallback() {
  FlutterForegroundTask.setTaskHandler(MusicTaskHandler());
}

class MusicTaskHandler extends TaskHandler {
  @override
  Future<void> onStart(DateTime timestamp, TaskStarter starter) async {
    print('onStart');
    while (true) {
      await Future.delayed(const Duration(minutes: 1)); // 每隔一分钟检查一次
      // 这里可以添加更多的后台任务逻辑
    }
  }

  @override
  Future<void> onDestroy(DateTime timestamp) async {
    print('onDestroy');
    // 在这里可以执行一些清理任务，例如停止音乐或释放资源
  }

  @override
  void onReceiveData(Object data) {
    print('onReceiveData: $data');
  }

  @override
  void onNotificationButtonPressed(String id) {
    print('onNotificationButtonPressed: $id');
  }

  @override
  void onNotificationPressed() {
    FlutterForegroundTask.launchApp('/'); // 跳转到应用首页
    print('onNotificationPressed');
  }

  @override
  void onNotificationDismissed() {
    print('onNotificationDismissed');
  }

  @override
  Future<void> onRepeatEvent(DateTime timestamp) async {
    // 每隔一段时间会调用此方法，可以在这里执行你需要的逻辑
    print('onRepeatEvent: $timestamp');
    // 可以在这里与 MusicState 进行交互，例如检查播放状态
  }
}

class MyApp extends StatefulWidget {
  MyApp({super.key, this.home = true});

  final bool home;

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _initService(); // 初始化服务
    // print('--- ${widget.home}');
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        // 当应用从后台回到前台时重新启动前台任务
        _initService();
        break;
      case AppLifecycleState.paused:
        // 当应用进入后台时不需要停止前台任务，因为我们需要保持音乐播放
        break;
      default:
        break;
    }
  }

  Future<void> _requestPermissions() async {
    // Android 13+, you need to allow notification permission to display foreground service notification.
    final NotificationPermission notificationPermission =
        await FlutterForegroundTask.checkNotificationPermission();
    if (notificationPermission != NotificationPermission.granted) {
      await FlutterForegroundTask.requestNotificationPermission();
    }

    if (Platform.isAndroid) {
      // "android.permission.SYSTEM_ALERT_WINDOW" permission must be granted for this function to be called.
      final bool? result =
          await FlutterForegroundTask.openSystemAlertWindowSettings();
      if (result ?? false) {
        // Permission has been granted.
      } else {
        // Permission has not been granted.
        print("Permission not granted for system alert window.");
      }
    }
  }

  Future<void> _initService() async {
    // await _requestPermissions();
    FlutterForegroundTask.init(
      androidNotificationOptions: AndroidNotificationOptions(
        channelId: 'music_player_channel',
        channelName: 'Music Player Service',
        channelDescription:
            'This notification shows that the music player is running in the background.',
        channelImportance: NotificationChannelImportance.LOW,
        priority: NotificationPriority.LOW,
        // notificationTitle: 'Music Player', // 添加通知标题
        // notificationText: 'Playing in the background...', // 添加通知文本
        // iconData: 'ic_launcher', // 确保你的资源文件中有这个图标
      ),
      iosNotificationOptions: const IOSNotificationOptions(
        showNotification: true,
        playSound: false,
      ),
      foregroundTaskOptions: ForegroundTaskOptions(
        eventAction: ForegroundTaskEventAction.repeat(5000),
        autoRunOnBoot: true,
        autoRunOnMyPackageReplaced: true,
        allowWakeLock: true,
        allowWifiLock: true,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '灵动 AI',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
        highlightColor: Colors.transparent,
        splashColor: Colors.transparent,
        scaffoldBackgroundColor: const Color(0xFF010101),
        appBarTheme: const AppBarTheme(
          color: Color(0xFF010101),
          iconTheme: IconThemeData(
            color: Color(0xFFFFFFFF),
            size: 20,
          ),
          titleTextStyle: TextStyle(
            color: Color(0xFFFFFFFF),
            fontSize: 15,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
      home: const HomePage(),
      //  initialRoute: '/',
      onGenerateRoute: (settings) {
        return onGenerateRoute(settings);
      },
    );
  }
}
